﻿using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebJobAsTimerService
{
    public class EmailService
    {
        //private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly ExchangeService _exchangeOnlineService;
        private readonly EmailAddress _fromAddress;

        public EmailService(IConfiguration configuration)
        {
            _fromAddress = new EmailAddress(configuration.FromAddress);

            //https://msdn.microsoft.com/EN-US/library/office/dn509511(v=exchg.150).aspx
            _exchangeOnlineService = new ExchangeService();
            _exchangeOnlineService.Credentials = new WebCredentials(configuration.ExchangeUserName, configuration.ExchangeUserPassword);
            _exchangeOnlineService.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
        }

        public void SendEmail(string toAddress, string subject, string messageBody, bool isMessageBodyInHtml)
        {
            EmailMessage emailMessage = new EmailMessage(_exchangeOnlineService);
            emailMessage.ToRecipients.Add(toAddress);
            emailMessage.From = _fromAddress;
            emailMessage.Subject = subject;

            emailMessage.Body = messageBody;
            if (isMessageBodyInHtml)
                emailMessage.Body.BodyType = BodyType.HTML;

            emailMessage.Send();
        }
    }
}
